package com.htzos.common.interceptor;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.htzos.admin.log.service.LogReqBaseService;
import com.htzos.admin.system.bean.SystemUserBase;
import com.htzos.common.util.CommonUtil;

/**
 * 验证权限，对登录的用户进行权限验证，只能访问有权限的路径
 *
 * @author xudz
 * @time 2017 2017年1月18日 上午10:22:12
 */
public final class AdminInterceptor extends HandlerInterceptorAdapter {

	private Logger logger=Logger.getLogger(AdminInterceptor.class);
	
	@Resource
	private LogReqBaseService logReqBaseService;
	
	/** 
     * preHandle方法是进行处理器拦截用的，顾名思义，该方法将在Controller处理之前进行调用，SpringMVC中的Interceptor拦截器是链式的，可以同时存在 
     * 多个Interceptor，然后SpringMVC会根据声明的前后顺序一个接一个的执行，而且所有的Interceptor中的preHandle方法都会在 
     * Controller方法调用之前调用。SpringMVC的这种Interceptor链式结构也是可以进行中断的，这种中断方式是令preHandle的返 
     * 回值为false，当preHandle的返回值为false的时候整个请求就结束了。 
     */ 
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean handlerOk =  super.preHandle(request, response, handler);
		
		if(!handlerOk) {
			return false;
		}
		HttpSession session = request.getSession();
		//设置基础路径
		HttpServletRequest httpRequest = request;
		HttpServletResponse httpResponse = response;
		
		String servletPath = httpRequest.getServletPath();
        SystemUserBase user = (SystemUserBase)session.getAttribute(CommonUtil.CURRENTUSER);
		
        if (user == null){
				httpResponse.sendRedirect(httpRequest.getContextPath() + "/toLogin"
						+ "?fromurl=" + httpRequest.getRequestURI());
				return false;
        }else{
    		//判断是否有权限
    		Map<String, String> roleMap = (Map<String, String>)session.getAttribute(CommonUtil.ROLE_MAP);
    		
    		if(!roleMap.containsKey(".."+servletPath)){
    			httpResponse.sendRedirect(httpRequest.getContextPath() + "/noRight");
    			return false;
    		}
        	
        }
        
		return true;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
		//设置调用的地址
		super.postHandle(request, response, handler, modelAndView);
	};
	
	
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}
}

